<html>
<head>
<style>
body {
  min-width:400px;
  overflow-x:hidden;
}

img {
  margin:5px;
  border:1px solid black;
  vertical-align:middle;
  width:75px;
  height:75px;
}
</style>

<script>
var req = new XMLHttpRequest();
var timerId;
function init() {	
	var loadingLabel = document.createElement("h3");
	loadingLabel.innerHTML = chrome.i18n.getMessage("loading");
	document.body.appendChild(loadingLabel);
	timerId = window.setTimeout(load,1);
}

function load() {
	req.open(
		"GET",
		"http://api-search.safecreative.org/v2/?" +
		    "component=search.byfields&" +
			"format=json&" + 
			"field1=workType.code&value1=photo&" +
		    "page=1",
		true);
	req.onload = showPhotos;
	req.send();
	clearTimeout(timerId);
}


function showPhotos() {
	document.body.removeChild(document.body.getElementsByTagName("h3")[0]);
	var result = JSON.parse(req.responseText);	;
  	var list = result.listpage.list;
  	for (var i = 0, work; work = list[i]; i++) {
		if(work.thumbnail) {
			var link = document.createElement("a");
	    	var img = document.createElement("image");
		    img.src = work.thumbnail;
			link.work = work;
			link.title = work.title + "\n" + work.license.shortname + " " + getCredits(work);
			link.onclick=function() {
				 chrome.tabs.create({url:this.work["human-url"]});
			}
			link.appendChild(img);
    		document.body.appendChild(link);
		}
	}
}

function getCredits(work) {
	var credits;
	if(work.authors && work.authors.author) {
		credits = work.authors.author.name;
	}else if(work["right-holders"] && work["right-holders"]["right-holder"]) {
		credits = work["right-holders"]["right-holder"].name;
	}
	return credits;	
}
</script>
</head>
<body onload="init()"></body>
</html>
